/**
//给你一个二叉树，请你返回其按 层序遍历 得到的节点值。 （即逐层地，从左到右访问所有节点）。 
//
// 
//
// 示例： 
//二叉树：[3,9,20,null,null,15,7], 
//
// 
//    3
//   / \
//  9  20
//    /  \
//   15   7
// 
//
// 返回其层序遍历结果： 
//
// 
//[
//  [3],
//  [9,20],
//  [15,7]
//]
// 
// Related Topics 树 广度优先搜索 二叉树 👍 1071 👎 0

*/

package com.xixi.dataStructure.tree.binaryTree;

import com.xixi.dataStructure.tree.TreeNode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

public class ID00102BinaryTreeLevelOrderTraversal {
public static void main(String[] args) {
Solution solution = new ID00102BinaryTreeLevelOrderTraversal().new Solution();
}


//leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {

    List<List<Integer>> resList = new ArrayList<List<Integer>>();


    Queue<TreeNode> nextlevel = new ArrayDeque<>();
    Queue<TreeNode> thislevel = new ArrayDeque<>();

    public List<List<Integer>> levelOrder(TreeNode root) {

        if(root==null) return resList;

        thislevel.add(root);
        List<Integer> levelList;

        while(!thislevel.isEmpty()){ //跳到下一层
            nextlevel.clear();//清空下一层容器
            levelList = new ArrayList<>();
            while(!thislevel.isEmpty()){ //循环当前一层循环，添加子节点层
                TreeNode nowNode = thislevel.poll();
                levelList.add(nowNode.val);
                if(nowNode.left!=null) nextlevel.add(nowNode.left);
                if(nowNode.right!=null) nextlevel.add(nowNode.right);
            }
            resList.add(levelList);
            thislevel = nextlevel; //下一层赋值为循环层

        }

        return resList;
    }


}
//leetcode submit region end(Prohibit modification and deletion)




}